package com.sky.controller.admin;

import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common/upload")
@Slf4j
@Api(tags = "文件上传接口")
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private AliOssProperties aliOssProperties;

    @PostMapping
    @ApiOperation("上传文件到OSS")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("接收到文件上传请求，文件名：{}", file.getOriginalFilename());

        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 使用配置中的目录名
            String fileName = UUID.randomUUID().toString() + suffix;
            String fullPath = aliOssProperties.getDirName() + "/" + fileName;

            String url = aliOssUtil.upload(file.getBytes(), fullPath);
            log.info("文件上传成功，URL：{}", url);

            return Result.success(url);

        } catch (IOException e) {
            log.error("文件读取失败", e);
            return Result.error("文件读取失败");
        } catch (Exception e) {
            log.error("OSS上传失败", e);
            return Result.error("上传失败：" + e.getMessage());
        }
    }
}